package com.shenmazong.order.service.impl;

import com.shenmazong.order.db.TbMessage;
import com.shenmazong.order.service.ITbMessageService;
import com.shenmazong.utils.ResultResponse;
import com.shenmazong.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * @author 军哥
 * @version 1.0
 * @description: ITbMessageServiceImpl
 * @date 2022/8/6 9:14
 */

@Service
public class ITbMessageServiceImpl implements ITbMessageService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResultResponse list(PageVo pageVo) {
        //--1 构造分页
        Query query = new Query();
        Integer skip = (pageVo.getPageNum() - 1) * pageVo.getPageSize();
        query.skip(skip).limit(pageVo.getPageSize());

        //--2 构造查询条件
        Criteria type = Criteria.where("type").is(1);
        query.addCriteria(type);
        // 根据时间排序
        query.with(Sort.by(Sort.Order.desc("createTime")));

        //--3 查询
        long count = mongoTemplate.count(query, TbMessage.class);
        List<TbMessage> tbMessages = mongoTemplate.find(query, TbMessage.class);

        //--4 返回结果
        HashMap<String, Object> map = new HashMap<>();
        map.put("records", tbMessages);
        map.put("total", count);
        map.put("pageNum", pageVo.getPageNum());
        map.put("pageSize", pageVo.getPageSize());

        Integer pages = 0;
        if(count%pageVo.getPageSize() > 0) {
            pages = (int)count / pageVo.getPageSize() + 1;
        }
        else {
            pages = (int)count / pageVo.getPageSize();
        }
        map.put("pages", pages);

        return ResultResponse.SUCCESS(map);
    }
}
